package chapter_22.io.other;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 利用输入、输出字符流复制文件
 */
public class FileCopy {

    public static void main(String[] args) {

        new File("./src/chapter_22/io/other/copy_build.txt").delete();// 每次运行前删除复制文件

        fileCopy();

    }

    private static void fileCopy(){
        // 开始时间
        long startTime = System.nanoTime();

        try (FileReader fileReader = new FileReader("./src/chapter_22/io/other/new_build.txt");
             FileWriter fileWriter = new FileWriter("./src/chapter_22/io/other/copy_build.txt")
        ) {

            // 准备一个缓冲区
            char[] chars = new char[1024];
            // 首先读取一次
            int len = fileReader.read(chars);

            while (len != -1) {
                String copyStr = new String(chars);
                // 打印复制的字符串
                System.out.println(copyStr);
                // 开始写入数据
                fileWriter.write(chars, 0, len);
                len = fileReader.read(chars);
            }

            System.out.println("useTime = " + (System.nanoTime() - startTime) + "纳秒" );

        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
